#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
训练执行脚本
直接执行epoch-based训练，无需手动输入参数
"""

import os
import sys
import subprocess
from pathlib import Path

def main():
    """主函数"""
    print("🚀 开始执行Epoch-based训练")
    print("=" * 60)
    
    # 训练配置 - 合理学习率衰减配置
    config_file = "configs/potsdam/H_48_D_4_proto_optimized.json"
    steps_per_epoch = 149  # 每epoch的步数
    target_epochs = 20     # 目标epoch数 (保证学习率有效衰减)
    max_iters = steps_per_epoch * target_epochs  # 计算需要的总迭代数
    
    print(f"📊 配置文件: {config_file}")
    print(f"🔄 每epoch步数: {steps_per_epoch}")
    print(f"📅 目标epoch数: {target_epochs}")
    print(f"🔄 最大迭代数: {max_iters}")
    print(f"⏱️ 预计训练时间: {max_iters * 1.5 / 60:.1f}分钟 ({max_iters * 1.5 / 3600:.1f}小时)")
    print("=" * 60)
    
    # 检查配置文件是否存在
    if not os.path.exists(config_file):
        print(f"❌ 配置文件不存在: {config_file}")
        return False
    
    # 构建训练命令
    cmd = [
        "python", "formal_training.py",
        "--config", config_file,
        "--max-iters", str(max_iters)
    ]
    
    print(f"🔧 执行命令: {' '.join(cmd)}")
    print("=" * 60)
    
    try:
        # 执行训练命令
        result = subprocess.run(cmd, check=True, capture_output=False)
        
        if result.returncode == 0:
            print("\n🎉 训练成功完成!")
            return True
        else:
            print(f"\n❌ 训练失败，返回码: {result.returncode}")
            return False
            
    except subprocess.CalledProcessError as e:
        print(f"\n❌ 训练执行失败: {e}")
        return False
    except KeyboardInterrupt:
        print(f"\n⏹️ 训练被用户中断")
        return False
    except Exception as e:
        print(f"\n❌ 训练过程中出现错误: {e}")
        return False

if __name__ == "__main__":
    success = main()
    
    if success:
        print("\n✅ 训练脚本执行成功")
    else:
        print("\n❌ 训练脚本执行失败")
    
    sys.exit(0 if success else 1)
